﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;

namespace HomeService.Models
{
    public class ServiceRequest : ViewModelBase
    {
        private readonly ObservableCollection<ServiceRequestPhoto> _photos;

        public ServiceRequest()
        {
            BasicInfo = new ServiceRequestBasicInfo();
            _photos = new ObservableCollection<ServiceRequestPhoto>();
        }

        public ServiceRequestBasicInfo BasicInfo { get; set; }

        public ReadOnlyObservableCollection<ServiceRequestPhoto> Photos
        {
            get { return new ReadOnlyObservableCollection<ServiceRequestPhoto>(_photos); }
        }

        public void AddPhoto(Stream imageStream)
        {
            _photos.Add(new ServiceRequestPhoto(imageStream, this));
        }

        public void RemovePhoto(ServiceRequestPhoto photo)
        {
            _photos.Remove(photo);
        }
        
        public void Send()
        {
            Validate();
            // TODO: Send the request
            Clear();
        }

        private void Validate()
        {
            var errors = new List<string>();
            if (string.IsNullOrEmpty(BasicInfo.Name))
                errors.Add("Nimi on pakollinen.");
            if (string.IsNullOrEmpty(BasicInfo.StreetAddress))
                errors.Add("Osoite on pakollinen.");
            if (string.IsNullOrEmpty(BasicInfo.PostalCode))
                errors.Add("Postinumero on pakollinen.");
            if (string.IsNullOrEmpty(BasicInfo.City))
                errors.Add("Postitoimipaikka on pakollinen.");
            if (string.IsNullOrEmpty(BasicInfo.Phone))
                errors.Add("Puhelinnumero on pakollinen.");
            if (string.IsNullOrEmpty(BasicInfo.Description))
                errors.Add("Ongelman kuvaus on pakollinen.");
            if (Photos.Count == 0)
                errors.Add("Liitä ainakin yksi valokuva huoltopyyntöön.");
            // Throw validation errors as exception
            if (errors.Count > 0) {
                var builder = new StringBuilder();
                foreach (var error in errors)
                    builder.Append(string.Format("- {0}\n", error));
                throw new ValidationException(builder.ToString());
            }
        }

        private void Clear()
        {
            BasicInfo.Clear();
            _photos.Clear();
        }
    }
}